<?php

ini_set("memory_limit", "-1");
header("Content-Type: text/html; charset=utf-8");
require('db.php');
$q = $_GET['q'];
$len = mb_strlen($q, 'utf-8');
$len_min = $len / 2;
if (function_exists('mb_string')) {
    echo "hi";
}

class Serial {
    public $id;
    public $name;
    public $category;
    public $imagelink;
    public $score;
    public $name_len;
    function Serial($id, $name, $category, $imagelink, $score) {
        $this->id = $id;
        $this->name = $name;
        $this->category = $category;
        $this->imagelink = $imagelink;
        $this->score = $score;
        $this->name_len = mb_strlen($name, 'utf-8');
    }
}

function GetScore($title) {
    $title_len = mb_strlen($title, 'utf-8');
    global $len;
    global $q;
    for ($i = 0; $i <= $len; $i++) {
        for ($j = 0; $j <= $title_len; $j++) {
            if ($i == 0 || $j == 0) {
                $dp[$i][$j] = 0;
            }
            else if (mb_substr($title, $j - 1, 1, 'utf-8') == mb_substr($q, $i - 1, 1, 'utf-8')) {
                $dp[$i][$j] =  max($dp[$i - 1][$j], $dp[$i][$j - 1], $dp[$i - 1][$j - 1] + 1);
            }
            else {
                $dp[$i][$j] =  max($dp[$i - 1][$j], $dp[$i][$j - 1]);
            }
            if ($i == $len && $j == $title_len) {
                return $dp[$i][$j];
            }
        }
    }
}

function mycmp($s1, $s2) {
    if ($s1->score != $s2->score) {
        return $s1->score > $s2->score ? -1 : 1;
    }
    if ($s1->name_len != $s2->name_len) {
        return $s1->name_len < $s2->name_len ? -1 : 1;
    }
    return -strcasecmp($s1->name, $s2->name);
}

$serials = array();
$sql = "select id, name, category, imagelink from serial";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    $score = GetScore($row['name']);
    if ($score >= $len_min) {
        array_push($serials, new Serial($row['id'], $row['name'], $row['category'], $row['imagelink'], $score));
    }
}
usort($serials, "mycmp");
$cnt = min(10, count($serials));
for ($i = 0; $i < $cnt; $i++) {
    echo '<p>' . $serials[$i]->id . '《' . $serials[$i]->name . '》' . $serials[$i]->imagelink . ' ' . $serials[$i]->score . '</p>';
}

?>
